import React, { useState, useEffect } from "react";
import { Modal, Descriptions, Tag, Space, Button, Divider, Typography, message, Card, Spin, Collapse } from "antd";
import {
  ClockCircleOutlined,
  FileTextOutlined,
  DownloadOutlined,
  UserOutlined,
  BookOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  RobotOutlined,
  ReloadOutlined,
  BulbOutlined,
} from "@ant-design/icons";
import styled from "styled-components";

const { Text, Paragraph } = Typography;
const { Panel } = Collapse;

const AIExplanationSection = styled.div`
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
`;

const QuestionCard = styled(Card)`
  margin-bottom: 16px;
  border: 1px solid #d9d9d9;
  
  .ant-card-head {
    background-color: #fafafa;
    border-bottom: 1px solid #d9d9d9;
  }
`;

const AnswerSection = styled.div`
  margin: 12px 0;
  padding: 12px;
  border-radius: 6px;
  background-color: #f8f9fa;
`;

const CorrectAnswer = styled.div`
  color: #52c41a;
  font-weight: bold;
`;

const WrongAnswer = styled.div`
  color: #ff4d4f;
  font-weight: bold;
`;

interface Question {
  id: string;
  question: string;
  type: "single" | "multiple" | "text";
  options?: string[];
  correctAnswer?: string | string[];
  studentAnswer?: string | string[];
  isCorrect?: boolean;
  score?: number;
  fullScore?: number;
  explanation?: string;
}

interface Homework {
  id: string;
  title: string;
  course: string;
  teacher: string;
  description: string;
  deadline: string;
  status: "未提交" | "已提交" | "已批改" | "已过期";
  type?: "file" | "quiz";
  score?: number;
  fullScore?: number;
  submittedAt?: string;
  gradedAt?: string;
  feedback?: string;
  attachments?: string[];
  submittedFiles?: string[];
  questions?: Question[];
  hasAIExplanation?: boolean;
}

interface HomeworkDetailModalProps {
  visible: boolean;
  homeworkId: string;
  onClose: () => void;
  viewAnswerMode?: boolean;
}

const HomeworkDetailModal: React.FC<HomeworkDetailModalProps> = ({
  visible,
  homeworkId,
  onClose,
  viewAnswerMode = false,
}) => {
  const [homework, setHomework] = useState<Homework | null>(null);
  const [loading, setLoading] = useState(false);
  const [aiExplanations, setAiExplanations] = useState<Record<string, string>>({});
  const [aiLoading, setAiLoading] = useState(false);
  const [showAIExplanation, setShowAIExplanation] = useState(false);

  // 获取作业详情
  const fetchHomeworkDetail = async () => {
    if (!homeworkId) return;
    
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟作业详情数据
      let mockHomework: Homework;
      
      if (homeworkId === "18") {
        // 数据库基础知识测试
        mockHomework = {
          id: homeworkId,
          title: "数据库基础知识测试",
          course: "数据库系统原理",
          teacher: "李教授",
          description: "测试对数据库基本概念、SQL语句、范式理论等的掌握程度。包含单选题、多选题和问答题，全面考察数据库基础知识。",
          deadline: "2024-12-10 23:59",
          status: "已批改",
          type: "quiz",
          fullScore: 100,
          score: 78,
          submittedAt: "2024-12-10 14:30",
          gradedAt: "2024-12-12 16:45",
          feedback: "对基本概念掌握较好，但在复杂SQL查询和范式理解上还有提升空间。建议加强SQL语句练习和范式理论学习。",
          questions: [
            {
              id: "1",
              question: "以下哪个不是关系数据库的特点？",
              type: "single",
              options: ["A. 数据以表格形式存储", "B. 支持事务处理", "C. 数据以树形结构存储", "D. 支持SQL查询"],
              correctAnswer: "C",
              studentAnswer: "C",
              isCorrect: true,
              score: 10,
              fullScore: 10,
              explanation: "关系数据库以表格形式存储数据，不是树形结构。树形结构是层次数据库的特点。"
            },
            {
              id: "2",
              question: "SQL中用于查询数据的关键字是？",
              type: "single",
              options: ["A. INSERT", "B. SELECT", "C. UPDATE", "D. DELETE"],
              correctAnswer: "B",
              studentAnswer: "B",
              isCorrect: true,
              score: 10,
              fullScore: 10,
              explanation: "SELECT是SQL中用于查询数据的关键字。"
            },
            {
              id: "3",
              question: "以下哪些是数据库的范式？",
              type: "multiple",
              options: ["A. 第一范式", "B. 第二范式", "C. 第三范式", "D. 第四范式"],
              correctAnswer: ["A", "B", "C", "D"],
              studentAnswer: ["A", "B", "C"],
              isCorrect: false,
              score: 7,
              fullScore: 10,
              explanation: "数据库范式包括第一范式、第二范式、第三范式、BCNF范式、第四范式等。"
            },
            {
              id: "4",
              question: "请简述什么是数据库事务的ACID特性？",
              type: "text",
              correctAnswer: "原子性、一致性、隔离性、持久性",
              studentAnswer: "原子性、一致性、隔离性、持久性",
              isCorrect: true,
              score: 20,
              fullScore: 20,
              explanation: "ACID是数据库事务的四个基本特性：原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)、持久性(Durability)。"
            },
            {
              id: "5",
              question: "以下哪个SQL语句用于创建表？",
              type: "single",
              options: ["A. CREATE TABLE", "B. INSERT TABLE", "C. UPDATE TABLE", "D. DELETE TABLE"],
              correctAnswer: "A",
              studentAnswer: "B",
              isCorrect: false,
              score: 0,
              fullScore: 10,
              explanation: "CREATE TABLE是用于创建表的SQL语句。"
            },
            {
              id: "6",
              question: "以下哪些是SQL的DML语句？",
              type: "multiple",
              options: ["A. SELECT", "B. INSERT", "C. UPDATE", "D. DELETE"],
              correctAnswer: ["A", "B", "C", "D"],
              studentAnswer: ["A", "B", "C"],
              isCorrect: false,
              score: 7,
              fullScore: 10,
              explanation: "DML(Data Manipulation Language)包括SELECT、INSERT、UPDATE、DELETE等语句。"
            },
            {
              id: "7",
              question: "请解释什么是数据库索引，以及它的作用。",
              type: "text",
              correctAnswer: "数据库索引是一种数据结构，用于提高数据库查询性能。它通过建立指向数据的指针，减少查询时需要扫描的数据量，从而加快查询速度。",
              studentAnswer: "索引是数据库中的一种结构，可以提高查询速度。",
              isCorrect: false,
              score: 8,
              fullScore: 20,
              explanation: "数据库索引是一种数据结构，用于提高数据库查询性能。它通过建立指向数据的指针，减少查询时需要扫描的数据量，从而加快查询速度。"
            }
          ]
        };
      } else if (homeworkId === "19") {
        // 算法与数据结构测试
        mockHomework = {
          id: homeworkId,
          title: "算法与数据结构测试",
          course: "数据结构与算法",
          teacher: "陈教授",
          description: "测试对基本算法和数据结构的理解，包括时间复杂度、空间复杂度等。通过多种题型全面考察算法基础。",
          deadline: "2024-12-08 23:59",
          status: "已批改",
          type: "quiz",
          fullScore: 100,
          score: 85,
          submittedAt: "2024-12-08 16:20",
          gradedAt: "2024-12-10 11:30",
          feedback: "对基本算法掌握较好，但在复杂算法的时间复杂度分析上需要加强。建议多做算法分析练习。",
          questions: [
            {
              id: "1",
              question: "快速排序的平均时间复杂度是？",
              type: "single",
              options: ["A. O(n)", "B. O(n log n)", "C. O(n²)", "D. O(log n)"],
              correctAnswer: "B",
              studentAnswer: "B",
              isCorrect: true,
              score: 15,
              fullScore: 15,
              explanation: "快速排序的平均时间复杂度是O(n log n)，最坏情况下是O(n²)。"
            },
            {
              id: "2",
              question: "以下哪种数据结构是LIFO？",
              type: "single",
              options: ["A. 队列", "B. 栈", "C. 链表", "D. 树"],
              correctAnswer: "B",
              studentAnswer: "B",
              isCorrect: true,
              score: 15,
              fullScore: 15,
              explanation: "栈(Stack)是LIFO(Last In First Out)的数据结构，后进先出。"
            },
            {
              id: "3",
              question: "以下哪些是图的遍历算法？",
              type: "multiple",
              options: ["A. 深度优先搜索", "B. 广度优先搜索", "C. 中序遍历", "D. 后序遍历"],
              correctAnswer: ["A", "B"],
              studentAnswer: ["A", "B"],
              isCorrect: true,
              score: 20,
              fullScore: 20,
              explanation: "深度优先搜索(DFS)和广度优先搜索(BFS)是图的遍历算法，中序遍历和后序遍历是树的遍历算法。"
            },
            {
              id: "4",
              question: "冒泡排序的时间复杂度是？",
              type: "single",
              options: ["A. O(n)", "B. O(n log n)", "C. O(n²)", "D. O(log n)"],
              correctAnswer: "C",
              studentAnswer: "B",
              isCorrect: false,
              score: 0,
              fullScore: 10,
              explanation: "冒泡排序的时间复杂度是O(n²)，是一种简单的排序算法。"
            },
            {
              id: "5",
              question: "以下哪些是线性数据结构？",
              type: "multiple",
              options: ["A. 数组", "B. 链表", "C. 栈", "D. 队列"],
              correctAnswer: ["A", "B", "C", "D"],
              studentAnswer: ["A", "B", "C", "D"],
              isCorrect: true,
              score: 15,
              fullScore: 15,
              explanation: "数组、链表、栈、队列都是线性数据结构，元素之间存在一对一的关系。"
            },
            {
              id: "6",
              question: "请解释什么是递归，并说明其优缺点。",
              type: "text",
              correctAnswer: "递归是一种函数调用自身的编程技术。优点：代码简洁，易于理解；缺点：可能导致栈溢出，空间复杂度较高。",
              studentAnswer: "递归是函数调用自己，代码简单但可能栈溢出。",
              isCorrect: true,
              score: 20,
              fullScore: 25,
              explanation: "递归是一种函数调用自身的编程技术。优点：代码简洁，易于理解；缺点：可能导致栈溢出，空间复杂度较高。"
            }
          ]
        };
              } else if (homeworkId === "6") {
          // 软件工程需求分析
          mockHomework = {
            id: homeworkId,
            title: "软件工程需求分析",
            course: "软件工程",
            teacher: "赵教授",
            description: "完成一个在线购物系统的需求分析文档。要求包含功能需求、非功能需求、用例图等。",
            deadline: "2024-12-20 23:59",
            status: "已批改",
            type: "file",
            fullScore: 100,
            score: 92,
            submittedAt: "2024-12-19 16:45",
            gradedAt: "2024-12-23 10:30",
            feedback: "需求分析详细，用例图清晰，但缺少非功能性需求分析。建议补充性能、安全性等要求。",
            submittedFiles: ["需求分析文档.pdf", "用例图.vsd"],
            questions: [
              {
                id: "1",
                question: "需求分析完整性",
                type: "text",
                correctAnswer: "功能需求和非功能需求分析全面",
                studentAnswer: "功能需求分析全面，非功能需求分析不够详细",
                isCorrect: false,
                score: 35,
                fullScore: 40,
                explanation: "功能需求分析很好，但非功能需求分析需要加强。"
              },
              {
                id: "2",
                question: "用例图设计",
                type: "text",
                correctAnswer: "用例图清晰完整，覆盖主要功能",
                studentAnswer: "用例图清晰完整，覆盖主要功能",
                isCorrect: true,
                score: 30,
                fullScore: 30,
                explanation: "用例图设计很好，清晰表达了系统功能。"
              },
              {
                id: "3",
                question: "文档规范性",
                type: "text",
                correctAnswer: "文档格式规范，结构清晰",
                studentAnswer: "文档格式规范，结构清晰",
                isCorrect: true,
                score: 20,
                fullScore: 20,
                explanation: "文档格式规范，符合软件工程标准。"
              },
              {
                id: "4",
                question: "创新性和实用性",
                type: "text",
                correctAnswer: "需求分析具有创新性和实用性",
                studentAnswer: "需求分析具有实用性，创新性一般",
                isCorrect: false,
                score: 7,
                fullScore: 10,
                explanation: "实用性很好，但创新性有待提高。"
              }
            ]
          };
        } else if (homeworkId === "7") {
          // 计算机组成原理实验
          mockHomework = {
            id: homeworkId,
            title: "计算机组成原理实验",
            course: "计算机组成原理",
            teacher: "孙教授",
            description: "使用Logisim设计简单的CPU。要求实现基本的指令集和数据处理功能。",
            deadline: "2024-12-18 23:59",
            status: "已批改",
            type: "file",
            fullScore: 100,
            score: 88,
            submittedAt: "2024-12-17 14:20",
            gradedAt: "2024-12-20 09:15",
            feedback: "CPU设计基本正确，但缺少一些优化。建议改进指令执行效率，增加流水线设计。",
            submittedFiles: ["CPU.circ", "设计说明.pdf"],
            questions: [
              {
                id: "1",
                question: "CPU设计正确性",
                type: "text",
                correctAnswer: "CPU设计正确，能执行基本指令",
                studentAnswer: "CPU设计正确，能执行基本指令",
                isCorrect: true,
                score: 40,
                fullScore: 40,
                explanation: "CPU设计正确，基本功能实现良好。"
              },
              {
                id: "2",
                question: "指令集设计",
                type: "text",
                correctAnswer: "指令集设计合理，覆盖基本运算",
                studentAnswer: "指令集设计合理，覆盖基本运算",
                isCorrect: true,
                score: 25,
                fullScore: 25,
                explanation: "指令集设计合理，功能覆盖全面。"
              },
              {
                id: "3",
                question: "性能优化",
                type: "text",
                correctAnswer: "考虑了性能优化，如流水线设计",
                studentAnswer: "基本功能实现，但缺少性能优化",
                isCorrect: false,
                score: 15,
                fullScore: 25,
                explanation: "基本功能实现，但性能优化方面需要改进。"
              },
              {
                id: "4",
                question: "文档说明",
                type: "text",
                correctAnswer: "设计说明详细，易于理解",
                studentAnswer: "设计说明详细，易于理解",
                isCorrect: true,
                score: 8,
                fullScore: 10,
                explanation: "设计说明详细，文档质量很好。"
              }
            ]
          };
        } else if (homeworkId === "8") {
          // 高等数学作业
          mockHomework = {
            id: homeworkId,
            title: "高等数学作业",
            course: "高等数学(一)",
            teacher: "周教授",
            description: "完成微积分相关习题，包括求导、积分等。要求计算过程清晰，结果准确。",
            deadline: "2024-12-15 23:59",
            status: "已批改",
            type: "file",
            fullScore: 100,
            score: 85,
            submittedAt: "2024-12-14 18:30",
            gradedAt: "2024-12-16 14:20",
            feedback: "计算过程基本正确，但在某些复杂积分上存在错误。建议加强练习，提高计算准确性。",
            submittedFiles: ["数学作业.pdf"],
            questions: [
              {
                id: "1",
                question: "求导计算",
                type: "text",
                correctAnswer: "求导过程正确，结果准确",
                studentAnswer: "求导过程正确，结果准确",
                isCorrect: true,
                score: 30,
                fullScore: 30,
                explanation: "求导计算完全正确，过程清晰。"
              },
              {
                id: "2",
                question: "积分计算",
                type: "text",
                correctAnswer: "积分计算正确，方法选择恰当",
                studentAnswer: "大部分积分计算正确，个别复杂积分有误",
                isCorrect: false,
                score: 25,
                fullScore: 35,
                explanation: "基本积分计算正确，但复杂积分需要加强练习。"
              },
              {
                id: "3",
                question: "计算过程",
                type: "text",
                correctAnswer: "计算过程清晰，步骤完整",
                studentAnswer: "计算过程清晰，步骤完整",
                isCorrect: true,
                score: 20,
                fullScore: 20,
                explanation: "计算过程清晰，步骤完整，便于理解。"
              },
              {
                id: "4",
                question: "应用能力",
                type: "text",
                correctAnswer: "能正确应用微积分解决实际问题",
                studentAnswer: "能应用微积分解决大部分问题",
                isCorrect: false,
                score: 10,
                fullScore: 15,
                explanation: "应用能力良好，但在复杂问题处理上需要提高。"
              }
            ]
          };
        } else {
          // 默认文件作业
        mockHomework = {
          id: homeworkId,
          title: "数据结构实验一：线性表实现",
          course: "数据结构与算法",
          teacher: "陈教授",
          description: "本次实验要求实现顺序表和链表的插入、删除、查找等基本操作。具体要求如下：\n\n1. 实现顺序表的以下操作：\n   - 初始化顺序表\n   - 插入元素\n   - 删除元素\n   - 查找元素\n   - 遍历输出\n\n2. 实现链表的以下操作：\n   - 创建链表\n   - 插入节点\n   - 删除节点\n   - 查找节点\n   - 遍历输出\n\n3. 要求：\n   - 代码规范，注释完整\n   - 提供测试用例\n   - 分析时间复杂度\n   - 撰写实验报告",
          deadline: "2024-12-28 23:59",
          status: "已批改",
          type: "file",
          fullScore: 100,
          attachments: ["实验要求.pdf", "参考代码.zip", "测试数据.txt"],
          submittedAt: "2024-12-24 15:30",
          submittedFiles: ["seqlist.c", "linklist.c", "main.c", "实验报告.pdf"],
          score: 92,
          gradedAt: "2024-12-26 10:30",
          feedback: "代码实现正确，注释详细，测试用例覆盖全面。建议在时间复杂度分析部分可以更加详细，实验报告格式规范。",
          questions: [
            {
              id: "1",
              question: "代码规范性评分",
              type: "text",
              correctAnswer: "代码结构清晰，命名规范，注释完整",
              studentAnswer: "代码结构清晰，命名规范，注释完整",
              isCorrect: true,
              score: 25,
              fullScore: 25,
              explanation: "代码规范性很好，符合编程规范要求。"
            },
            {
              id: "2",
              question: "功能实现完整性",
              type: "text",
              correctAnswer: "顺序表和链表的基本操作都已实现",
              studentAnswer: "顺序表和链表的基本操作都已实现",
              isCorrect: true,
              score: 30,
              fullScore: 30,
              explanation: "所有要求的功能都已正确实现。"
            },
            {
              id: "3",
              question: "测试用例覆盖度",
              type: "text",
              correctAnswer: "测试用例覆盖了各种边界情况",
              studentAnswer: "测试用例覆盖了大部分情况",
              isCorrect: false,
              score: 20,
              fullScore: 25,
              explanation: "测试用例基本完整，但缺少一些边界情况的测试。"
            },
            {
              id: "4",
              question: "时间复杂度分析",
              type: "text",
              correctAnswer: "详细分析了各操作的时间复杂度",
              studentAnswer: "简单分析了时间复杂度",
              isCorrect: false,
              score: 12,
              fullScore: 20,
              explanation: "时间复杂度分析不够详细，建议补充更深入的分析。"
            }
          ]
        };
      }
      
      setHomework(mockHomework);
    } catch (error) {
      message.error("获取作业详情失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible && homeworkId) {
      fetchHomeworkDetail();
    }
  }, [visible, homeworkId]);

  // 如果是查看答案模式，自动显示AI解析
  useEffect(() => {
    if (viewAnswerMode && homework && homework.status === '已批改') {
      setShowAIExplanation(true);
      generateAIExplanations();
    }
  }, [viewAnswerMode, homework]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case "未提交":
        return "orange";
      case "已提交":
        return "blue";
      case "已批改":
        return "success";
      case "已过期":
        return "error";
      default:
        return "default";
    }
  };

  const handleDownloadAttachment = (filename: string) => {
    message.success(`开始下载: ${filename}`);
    // 这里可以添加实际的下载逻辑
  };

  const handleDownloadSubmittedFile = (filename: string) => {
    message.success(`开始下载: ${filename}`);
    // 这里可以添加实际的下载逻辑
  };

  // 生成AI解析
  const generateAIExplanations = async () => {
    if (!homework?.questions) return;

    setAiLoading(true);
    try {
      // 模拟AI解析生成
      const explanations: Record<string, string> = {};
      
      for (const question of homework.questions) {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800));
        
        let explanation = '';
        
        if (question.type === 'single') {
          if (question.isCorrect) {
            explanation = `✅ 回答正确！您选择了"${question.studentAnswer}"，这是正确答案。\n\n💡 解析：${question.explanation || '这道题目考察了基础概念的理解，您的答案完全正确。'}\n\n🔍 知识点：本题考查了相关概念的核心要点，建议您继续保持对基础知识的掌握。`;
          } else {
            explanation = `❌ 回答错误。您选择了"${question.studentAnswer}"，但正确答案是"${question.correctAnswer}"。\n\n💡 解析：${question.explanation || '这道题目需要仔细分析每个选项的含义，建议您重新理解相关概念。'}\n\n🔍 学习建议：建议您复习相关知识点，加深对概念的理解。可以查阅教材或相关资料进行巩固。`;
          }
        } else if (question.type === 'multiple') {
          const studentAnswers = Array.isArray(question.studentAnswer) ? question.studentAnswer : [];
          const correctAnswers = Array.isArray(question.correctAnswer) ? question.correctAnswer : [];
          
          if (question.isCorrect) {
            explanation = `✅ 回答正确！您选择了${studentAnswers.join('、')}，这些都是正确答案。\n\n💡 解析：${question.explanation || '这道多选题考察了多个相关概念，您的选择完全正确。'}\n\n🔍 知识点：本题考查了多个相关概念的综合应用，您的理解很到位。`;
          } else {
            const missing = correctAnswers.filter(a => !studentAnswers.includes(a));
            const extra = studentAnswers.filter(a => !correctAnswers.includes(a));
            
            explanation = `❌ 回答部分错误。\n\n您的选择：${studentAnswers.join('、')}\n正确答案：${correctAnswers.join('、')}`;
            
            if (missing.length > 0) {
              explanation += `\n\n❌ 缺少：${missing.join('、')}`;
            }
            if (extra.length > 0) {
              explanation += `\n\n❌ 多余：${extra.join('、')}`;
            }
            
            explanation += `\n\n💡 解析：${question.explanation || '这道多选题需要全面考虑所有正确选项，建议您仔细分析每个选项。'}\n\n🔍 学习建议：多选题需要全面掌握相关概念，建议您系统复习相关知识点。`;
          }
        } else if (question.type === 'text') {
          if (question.isCorrect) {
            explanation = `✅ 回答正确！您的答案：${question.studentAnswer}\n\n💡 解析：${question.explanation || '您的回答准确完整，体现了对知识点的深入理解。'}\n\n🔍 知识点：本题考查了综合应用能力，您的回答展现了良好的理解深度。`;
          } else {
            explanation = `❌ 回答需要改进。\n\n您的答案：${question.studentAnswer}\n参考答案：${question.correctAnswer}\n\n💡 解析：${question.explanation || '建议您重新理解相关概念，补充遗漏的知识点。'}\n\n🔍 学习建议：可以查阅相关教材或资料，加深对知识点的理解。建议多做相关练习来巩固。`;
          }
        }
        
        explanations[question.id] = explanation;
      }
      
      setAiExplanations(explanations);
      setShowAIExplanation(true);
      message.success('AI解析生成完成！');
    } catch (error) {
      message.error('AI解析生成失败，请稍后重试');
    } finally {
      setAiLoading(false);
    }
  };

  // 重新生成AI解析
  const regenerateAIExplanations = async () => {
    setAiExplanations({});
    setShowAIExplanation(false);
    await generateAIExplanations();
  };

  if (!homework) {
    return null;
  }

  return (
    <Modal
      title={
        <Space>
          <FileTextOutlined />
          作业详情
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={[
        <Button key="close" onClick={onClose}>
          关闭
        </Button>,
        homework?.status === '已批改' && (
          <Button 
            key="ai" 
            type="primary" 
            icon={<RobotOutlined />}
            loading={aiLoading}
            onClick={showAIExplanation ? regenerateAIExplanations : generateAIExplanations}
          >
            {showAIExplanation ? '重新生成AI解析' : '生成AI解析'}
          </Button>
        )
      ].filter(Boolean)}
      width={800}
      confirmLoading={loading}
    >
      <Descriptions column={2} bordered>
        <Descriptions.Item label="作业标题" span={2}>
          <Text strong>{homework.title}</Text>
        </Descriptions.Item>
        
        <Descriptions.Item label="所属课程">
          <Space>
            <BookOutlined />
            <Tag color="cyan">{homework.course}</Tag>
          </Space>
        </Descriptions.Item>
        
        <Descriptions.Item label="任课教师">
          <Space>
            <UserOutlined />
            <Tag color="purple">{homework.teacher}</Tag>
          </Space>
        </Descriptions.Item>
        
        <Descriptions.Item label="作业状态">
          <Tag color={getStatusColor(homework.status)}>
            {homework.status === "已批改" && <CheckCircleOutlined />}
            {homework.status}
          </Tag>
        </Descriptions.Item>
        
        <Descriptions.Item label="满分">
          <Text strong>{homework.fullScore}分</Text>
        </Descriptions.Item>
        
        <Descriptions.Item label="截止时间" span={2}>
          <Space>
            <ClockCircleOutlined />
            <Text>{homework.deadline}</Text>
          </Space>
        </Descriptions.Item>
        
        <Descriptions.Item label="作业描述" span={2}>
          <Paragraph style={{ whiteSpace: "pre-line" }}>
            {homework.description}
          </Paragraph>
        </Descriptions.Item>
        
        {homework.attachments && homework.attachments.length > 0 && (
          <Descriptions.Item label="附件下载" span={2}>
            <Space wrap>
              {homework.attachments.map((file, index) => (
                <Button
                  key={index}
                  type="link"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownloadAttachment(file)}
                >
                  {file}
                </Button>
              ))}
            </Space>
          </Descriptions.Item>
        )}
        
        {homework.submittedAt && (
          <Descriptions.Item label="提交时间" span={2}>
            <Space>
              <ClockCircleOutlined />
              <Text>{homework.submittedAt}</Text>
            </Space>
          </Descriptions.Item>
        )}
        
        {homework.submittedFiles && homework.submittedFiles.length > 0 && (
          <Descriptions.Item label="已提交文件" span={2}>
            <Space wrap>
              {homework.submittedFiles.map((file, index) => (
                <Button
                  key={index}
                  type="link"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownloadSubmittedFile(file)}
                >
                  {file}
                </Button>
              ))}
            </Space>
          </Descriptions.Item>
        )}
        
        {homework.score !== undefined && (
          <Descriptions.Item label="得分">
            <Text strong style={{ color: "#52c41a", fontSize: "16px" }}>
              {homework.score}/{homework.fullScore}
            </Text>
          </Descriptions.Item>
        )}
        
        {homework.gradedAt && (
          <Descriptions.Item label="批改时间">
            <Space>
              <ClockCircleOutlined />
              <Text>{homework.gradedAt}</Text>
            </Space>
          </Descriptions.Item>
        )}
        
        {homework.feedback && (
          <Descriptions.Item label="教师反馈" span={2}>
            <div style={{ background: "#f6f8fa", padding: "12px", borderRadius: "6px" }}>
              <Space>
                <ExclamationCircleOutlined style={{ color: "#1890ff" }} />
                <Text>{homework.feedback}</Text>
              </Space>
            </div>
          </Descriptions.Item>
        )}
      </Descriptions>

      {/* AI解析部分 - 对所有已批改作业显示 */}
      {homework.status === '已批改' && (
        <div style={{ marginTop: 24 }}>
          <Divider>
            <Space>
              <RobotOutlined style={{ color: '#1890ff' }} />
              <Text strong>AI智能解析</Text>
            </Space>
          </Divider>

          {aiLoading && (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <Spin size="large" />
              <div style={{ marginTop: 16 }}>
                <Text>AI正在分析您的答题情况...</Text>
              </div>
            </div>
          )}

          {showAIExplanation && !aiLoading && (
            <div>
              <div style={{ marginBottom: 16, textAlign: 'right' }}>
                <Button 
                  icon={<ReloadOutlined />}
                  onClick={regenerateAIExplanations}
                  loading={aiLoading}
                >
                  重新生成
                </Button>
              </div>
              
              <Collapse defaultActiveKey={['1']} ghost>
                {homework.questions?.map((question, index) => (
                  <Panel 
                    header={`第 ${index + 1} 题 - ${question.type === 'single' ? '单选题' : question.type === 'multiple' ? '多选题' : '问答题'} (得分: ${question.score}/${question.fullScore})`}
                    key={question.id}
                  >
                    <QuestionCard
                      title={question.question}
                      extra={
                        <Tag color={question.isCorrect ? 'success' : 'error'}>
                          {question.isCorrect ? '正确' : '错误'}
                        </Tag>
                      }
                    >
                      {question.options && (
                        <div style={{ marginBottom: 16 }}>
                          <Text strong>选项：</Text>
                          <div style={{ marginTop: 8 }}>
                            {question.options.map((option, optIndex) => (
                              <div key={optIndex} style={{ margin: '4px 0' }}>
                                <Text style={{ 
                                  color: Array.isArray(question.correctAnswer) 
                                    ? question.correctAnswer.includes(option) ? '#52c41a' : '#666'
                                    : question.correctAnswer === option ? '#52c41a' : '#666'
                                }}>
                                  {option}
                                </Text>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}

                      <AnswerSection>
                        <div style={{ marginBottom: 8 }}>
                          <Text strong>您的答案：</Text>
                          {question.isCorrect ? (
                            <CorrectAnswer>
                              {Array.isArray(question.studentAnswer) 
                                ? question.studentAnswer.join('、') 
                                : question.studentAnswer}
                            </CorrectAnswer>
                          ) : (
                            <WrongAnswer>
                              {Array.isArray(question.studentAnswer) 
                                ? question.studentAnswer.join('、') 
                                : question.studentAnswer}
                            </WrongAnswer>
                          )}
                        </div>
                        
                        {!question.isCorrect && (
                          <div>
                            <Text strong>正确答案：</Text>
                            <CorrectAnswer>
                              {Array.isArray(question.correctAnswer) 
                                ? question.correctAnswer.join('、') 
                                : question.correctAnswer}
                            </CorrectAnswer>
                          </div>
                        )}
                      </AnswerSection>

                      {aiExplanations[question.id] && (
                        <AIExplanationSection>
                          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                            <BulbOutlined style={{ marginRight: 8 }} />
                            <Text strong style={{ color: 'white' }}>AI智能解析</Text>
                          </div>
                          <Paragraph style={{ color: 'white', margin: 0 }}>
                            {aiExplanations[question.id].split('\n').map((line, lineIndex) => (
                              <div key={lineIndex} style={{ marginBottom: line ? '8px' : '4px' }}>
                                {line}
                              </div>
                            ))}
                          </Paragraph>
                        </AIExplanationSection>
                      )}
                    </QuestionCard>
                  </Panel>
                ))}
              </Collapse>
            </div>
          )}

          {!showAIExplanation && !aiLoading && (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <RobotOutlined style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: 16 }} />
              <div>
                <Text type="secondary">点击"生成AI解析"按钮获取智能分析</Text>
              </div>
            </div>
          )}
        </div>
      )}
    </Modal>
  );
};

export default HomeworkDetailModal; 